//
//  WBStatus.m
//  新浪微博项目
//
//  Created by neng on 15/10/2.
//  Copyright © 2015年 neng. All rights reserved.
//

#import "WBStatus.h"
#import "WBPhoto.h"
#import "NSDate+MJ.h"

#import "WBEmotionTool.h"
#import "WBEmotion.h"

#import "WBPart.h"
#import "RegexKitLite.h"

@implementation WBStatus

//重写转发微博的setter方法来设置被抓发微博的用户的用户名
- (void)setRetweeted_status:(WBStatus *)retweeted_status
{
    _retweeted_status = retweeted_status;
    
    _retweetedName = [NSString stringWithFormat:@"@%@",retweeted_status.user.name];
    
     self.retweetedAtt_status = [self attributedTextWith:retweeted_status.text];
}

//实现这个方法就可以把对应的key转成对应的模型
+ (NSDictionary *)objectClassInArray
{
    return @{@"pic_urls":[WBPhoto class]};
}

//由于source不会频繁变动，所以不像日期，重写get方法
- (void)setSource:(NSString *)source
{
    //source =  <a href="http://weibo.com/" rel="nofollow">微博 weibo.com</a>
    
    //截取字符串
    //有时候来源的长度会是0
    if (source.length > 0) {
        NSRange range = [source rangeOfString:@">"];
        source = [source substringFromIndex:range.length + range.location];
        range = [source rangeOfString:@"<"];
        source = [source substringToIndex:range.location];
    }
    
    _source = source;
}

//返回日期
- (NSString *)created_at
{
    //Sun Oct 04 18:50:06 +0800 2015
    
    //转换格式
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    //这是新浪返回数据的时间格式
    fmt.dateFormat = @"EEE MMM d HH:mm:ss Z yyyy";
    //必须设置这个。不然解析不了
    fmt.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    
    //把返回的字符串转成日期
    NSDate *create_at = [fmt dateFromString:_created_at];
    
    //比较
    if ([create_at isThisYear]) { //今年
        
        if ([create_at isToday]) { //今天
            
            //计算时间差
            NSDateComponents *cmp = [create_at deltaWithNow];
            
            if (cmp.hour > 1) {
                return [NSString stringWithFormat:@"%ld小时之前",cmp.hour];
            }else if (cmp.minute > 1){
                return [NSString stringWithFormat:@"%ld分钟之前",cmp.minute];
            }else{
                return @"刚刚";
            }
        }else if ([create_at isYesterday]){ //昨天
            
            fmt.dateFormat = @"昨天 HH:mm";
            return [fmt stringFromDate:create_at];
            
        }else{ //前天
            
            fmt.dateFormat = @"MM-dd HH:mm";
            return [fmt stringFromDate:create_at];
        }
        
    }else{ // 不是今年
        
        fmt.dateFormat = @"yyyy-MM-dd HH:mm";
        return [fmt stringFromDate:create_at];
    }
    
    return _created_at;
}

//重写setText方法来设置属性文字
- (void)setText:(NSString *)text
{
    _text = text;
    
    self.attributedText = [self attributedTextWith:text];
}



//返回属性文字
- (NSAttributedString *)attributedTextWith:(NSString *)text
{
    //使用正则表达式分割处特殊的字符
    //@
    NSString *atPatten = @"@[0-9a-zA-Z\\u4e00-\\u9fa5-_]+";
    //表情
    NSString *emotioPatten = @"\\[[0-9a-zA-Z\\u4e00-\\u9fa5]+\\]";
    //话题
    NSString *topicPatten = @"#[0-9a-zA-Z\\u4e00-\\u9fa5]+#";
    //链接
    NSString *urlPatten = @"\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))";
    NSString *patten = [NSString stringWithFormat:@"%@|%@|%@|%@",atPatten,emotioPatten,topicPatten,urlPatten];
    
    //存放所有分段的数组
    NSMutableArray *parts = [NSMutableArray array];
    //取出匹配的字符串和范围
    [text enumerateStringsMatchedByRegex:patten usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        //如果是{0,0}代表结束
        if ((*capturedRanges).length == 0) {
            return ;
        }
        
        //创建对象
        WBPart *part = [[WBPart alloc] init];
        part.content = *capturedStrings;
        part.range = *capturedRanges;
        part.special = YES;
        if ([(*capturedStrings) hasPrefix:@"["] && [(*capturedStrings) hasSuffix:@"]"]) {
            part.emotion = YES;
        }
        
        //添加到数组
        [parts addObject:part];
    }];
    
    //取出其余的字符串和范围
    [text enumerateStringsSeparatedByRegex:patten usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        //如果是{0,0}代表结束
        if ((*capturedRanges).length == 0) {
            return ;
        }
        //创建对象
        WBPart *part = [[WBPart alloc] init];
        part.content = *capturedStrings;
        part.range = *capturedRanges;
        
        //添加到数组
        [parts addObject:part];
    }];
    
    //给数组排序
    [parts sortUsingComparator:^NSComparisonResult(WBPart *obj1, WBPart *obj2) {
        if (obj1.range.location > obj2.range.location) {
            return NSOrderedDescending;
        }else {
            return NSOrderedAscending;
        }
    }];
    
    //遍历数组拼接字符串
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init];
    for (WBPart *part in parts) {
        
        if (part.isEmotion) { // 表情
            //创建表情属性文字
            NSTextAttachment *att = [[NSTextAttachment alloc] init];
            NSAttributedString *imgStr = nil;
            //取出对应表情
            WBEmotion *emotion = [WBEmotionTool emotionWith:part.content];
            if (emotion.png) { //如果有图片才加载图片
                att.image = [UIImage imageNamed:emotion.png];
                att.bounds = CGRectMake(0, -3, WBTextSize + 3.5, WBTextSize + 3.5);
                imgStr = [NSAttributedString attributedStringWithAttachment:att];
            }else { //没有就显示文字
                imgStr = [[NSAttributedString alloc] initWithString:part.content];
            }
            //拼接
            [attStr appendAttributedString:imgStr];
            
        }else if (part.isSpecial) { //特殊
            
            NSAttributedString *str = [[NSAttributedString alloc] initWithString:part.content attributes:@{NSForegroundColorAttributeName:WBSpecialTextColor}];
            //拼接
            [attStr appendAttributedString:str];
            
        }else { //普通文字
            
            NSAttributedString *str = [[NSAttributedString alloc] initWithString:part.content];
            [attStr appendAttributedString:str];
        }
    }
    
    //修改字体大小
    [attStr addAttribute:NSFontAttributeName value:WBTextFont range:NSMakeRange(0, attStr.length)];
    
    return attStr;
}

@end
